import {PureComponent} from 'react';
import {
  Button,
  Card,
  Collapse,
  Row,
  Col,
  Avatar,
  Divider,
  Comment,
  Tooltip,
  message,
  Form,
  Popconfirm,
  Popover,
  Tag,
  BackTop,
  Image
} from 'antd';
import React from 'react';
import { connect } from 'umi';
import { getUrlParam } from '@/utils/ParamUtil';
import {
  CaretRightOutlined,
  CloseCircleOutlined,
  DislikeFilled,
  DislikeOutlined,
  LikeFilled,
  LikeOutlined,
  StarTwoTone
} from '@ant-design/icons';
import moment from "moment";
import { ReactEmojiEditor, ReactEmojiShow  } from 'react-emotor';
import {likeAction} from "@/pages/BlogInfo/service";
import {getCurrentUser} from "@/utils/globalService";
import {history} from "@@/core/history";
import {show} from "@/utils/NotificationUtil";
import {init} from "@/utils/WebSocketUtil";
import 'quill-emoji/dist/quill-emoji.css';
import styles from './style.less';

const { Panel } = Collapse;

class BlogInfo extends PureComponent {
  state = {
    commentList: [],
    blogId: null,
    action: [],
    replyVisible: null,
    currentUser: null,
    temp: '',
    sending: false,
    blogAction: [],
    replyName: '',
    parentId: null,
    replyId: null,
    cardHe: 0
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const id = getUrlParam(window.location.href, 'id');
    if (id){
      this.setState({ blogId: id });
      dispatch({
        type: 'blogInfo/queryById',
        payload: {
          id: id,
        }
      }).then(res => {
        if (res.status == 200){
          getCurrentUser().then(e => {
            if (e.status == 200){
              this.setState({ currentUser: e.data });
              //如果不是发布人则增加浏览量
              if (e.data.id != res.data.userId){
                dispatch({
                  type: 'blogInfo/blogAction',
                  payload: {
                    id: id,
                    views: res.data.views + 1,
                    action: 'view'
                  }
                })
              }
            }
          })
        }
      })
      this.refreshComment();
    }else {
      history.push('/welcome');
    }
  }

  refreshComment = () => {
    const { dispatch } = this.props;
    const id = getUrlParam(window.location.href, 'id');
    dispatch({
      type: 'blogInfo/queryComment',
      payload: {
        blogId: id,
      }
    }).then(res => {
      if (res.status == 200){
        this.setState({
          commentList: res.data
        })
      }
    })
  };

  like = (id, name) => {
    const  { action } = this.state;

    if (action.indexOf(id + '_like') > -1 || action.indexOf(id + '_dislike') > -1){
      return;
    }
    const params = {
      id: id,
      action: 'like'
    }
    likeAction(params).then(res => {
      if (res.status == 200){
        let act = action;
        act.push(id + '_like');
        this.setState({
          action: act
        });
        this.sendMessage('commentLike', name);
        message.success('已点赞');
        this.refreshComment();
        this.forceUpdate();
      }
    })
  };

  dislike = (id, name) => {
    const  { action } = this.state;
    if (action.indexOf(id + '_like') > -1 || action.indexOf(id + '_dislike') > -1){
      return;
    }
    const params = {
      id: id,
      action: 'dislike'
    }
    likeAction(params).then(res => {
      if (res.status == 200){
        let act = action;
        act.push(id + '_dislike');
        this.setState({
          action: act
        });
        this.sendMessage('commentDisLike', name);
        message.success('已踩');
        this.refreshComment();
        this.forceUpdate();
      }
    })
  };

  showReply = (replyName, replyId, parentId, flag) => {
    this.setState({
      replyName: replyName,
      replyId: replyId,
      parentId: parentId,
      replyVisible: flag
    });
    if (!flag){
      document.getElementById('emotor').innerHTML = '';
    }else {
      document.getElementById('emotor').scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
    }
  };

  reply = () => {
    const { dispatch } = this.props;
    const { replyId, parentId, replyName, temp } = this.state;
    if (temp == '' || temp == null){
      this.showReply('', null, null, false);
      return ;
    }
    dispatch({
      type: 'blogInfo/addComment',
      payload: {
        blogId: this.state.blogId,
        parentId: parentId ? parentId : 0,
        replyId: replyId,
        content: temp
      }
    }).then(res => {
      if (res.status == 200){
        this.sendMessage('commentReply', replyName);
        message.success('评论成功！');
        this.refreshComment();
        this.showReply('', null, null, false);
      }
    })
  };

  sendComment = () => {
    const { temp } = this.state;
    if (temp == '' || temp == null){
      return false;
    }
    const { dispatch, blogInfo: { data } } = this.props;
    this.setState({ sending: true });
    dispatch({
      type: 'blogInfo/addComment',
      payload: {
        blogId: this.state.blogId,
        parentId: 0,
        replyId: 0,
        content: temp
      }
    }).then(res => {
      if (res.status == 200){
        this.sendMessage('commentSend', data.loginName);
        message.success('评论成功！');
        this.refreshComment();
      }
      this.setState({ sending: false, temp: '' });
      document.getElementById('emotor').innerHTML = '';
    })
  };

  blogAction = type => {
    const { dispatch, blogInfo: { data } } = this.props;
    const { currentUser, blogId, blogAction } = this.state;
    if (currentUser.id == data.userId){
      message.warning(type == 'like' ? '不能点赞自己的博客哦！' : '不能收藏自己的博客哦！');
      return ;
    }
    if ((blogAction.length > 0 && type == 'like' && blogAction.indexOf('like') > -1) || (blogAction.length > 0 && type == 'star' && blogAction.indexOf('star') > -1)){
      return ;
    }
    dispatch({
      type: 'blogInfo/blogAction',
      payload: {
        id: blogId,
        action: type
      }
    }).then(res => {
      if (res.status == 200){
        let list = blogAction || [];
        list.push(type);
        this.setState({blogAction: list});
        message.success(type == 'like' ? '点赞成功！' : '收藏成功！');
        this.sendMessage(type == 'like' ? 'blogLike' : 'blogStar', data.loginName);
        dispatch({
          type: 'blogInfo/queryById',
          payload: {
            id: this.state.blogId
          }
        });
      }
    })
  };

  handleChg = e => {
    this.setState({ temp: e });
  };

  deleteComments = (id, name) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'blogInfo/deleteComments',
      payload: {
        id: id
      }
    }).then(res => {
      if (res.status == 200){
        this.sendMessage('commentDel', name);
        message.success('已删除');
        this.refreshComment();
      }
    })
  };

  sendMessage = (type, sendName) => {
    const { blogId, currentUser } = this.state;
    if (!window.socket){
      init(currentUser.loginName);
    }
    if (window.socket){
      let message = '';
      switch (type) {
        case 'blogLike': message = `赞了您的博客`
          break;
        case 'blogStar': message = `收藏了您的博客`
          break;
        case 'commentLike': message = `赞了您的评论`
          break;
        case 'commentDisLike': message = `踩了您的评论`
          break;
        case 'commentReply': message = `回复了您的评论`
          break;
        case 'commentDel': message = `删除了您的评论`
          break;
        case 'commentSend': message = `评论了您的博客`
          break;
        default: message = ''
          break;
      }
      window.socket.send(`message-/blogInfo?id=${blogId}-<span style="color: #7dd4b8">${currentUser.loginName}</span> ${message}|${sendName}`);
    }else {
      show('WebSocket错误', '失去连接', 'error');
    }
  };

  toUserInfo = id => {
    history.push('/userInfo?id=' + id);
  }

  render() {
    const {
      blogInfo: { data },
      loading,
    } = this.props;

    if (!data){
      return null;
    }

    const { commentList, action, replyVisible, currentUser, sending, replyName } = this.state;

    const IconText = ({ icon, text }) => (
      <span>
        {icon} {text}
      </span>
    );

    const popoverContent = item => (
      <div style={{ maxWidth: '450px', padding: '5px 0 0 5px'}}>
        <Row>
          <Col span={10}>
            <Image src={item.avatar} style={{ width: '100%' }}/>
          </Col>
          <Col span={14} style={{ padding: '0 0 0 2%' }}>
            <Row>
              <Col span={24}>
                  <span>
                    <a onClick={() => this.toUserInfo(item.userId)} style={{ fontWeight: '600', fontSize: '18px' }}>{item.loginName}</a>&nbsp;
                    <Tag color={item.role_id == 1 ? 'gold' : (item.role_id == 3 ? 'orange' : 'cyan')}>{item.roleName}</Tag>
                  </span>
              </Col>
            </Row>
            <Row style={{ marginTop: '5%' }}>
              <Col span={24}>
                <Tooltip title={item.signature ? (item.signature.length > 29 ? item.signature : '') : '暂无个人简介'}>
                  <span style={{ fontSize: '15px' }}>{item.signature && (item.signature.length > 29 ? item.signature.substring(0, 29) + '...' : item.signature) || `暂无个人简介`}</span>
                </Tooltip>
              </Col>
            </Row>
            <Row style={{ marginTop: '2%' }}>
              <Col span={24}>
                {item.tags ? item.tags.split(',').map((item) => <Tag style={{ marginTop: '3%' }}>{item}</Tag>) : `暂无标签`}
              </Col>
            </Row>
          </Col>
        </Row>
        <Divider />
        <Row>
          <Col span={12}>
            性别：{item.sex || '未知'}
          </Col>
          <Col span={12}>
            年龄：{item.age || '未知'}
          </Col>
        </Row>
        <Row style={{ marginTop: '2%' }}>
          <Col span={12}>
            邮箱：{item.email || '无'}
          </Col>
          <Col span={12}>
            电话：{item.phone || '无'}
          </Col>
        </Row>
      </div>
    )

    const nameLabel = ({loginName, role_id, userId}) => {
      const color = role_id == 1 ? 'gold' : (role_id == 3 ? 'darkorange' : '#1890ff');
      return <span onClick={() => this.toUserInfo(userId)} style={{ color: color, cursor: 'pointer', fontSize: '14px' }}>{loginName}</span>
    }

    return (
      <>
        <Card
          bordered={false}
          loading={loading}
          title={
            <Row>
              <Col span={4}>
                <Avatar onClick={() => this.toUserInfo(data.userId)} src={data.avatar} size={'large'} style={{ marginTop: '1px', cursor: 'pointer' }} />
              </Col>
              <Col span={6} pull={3}>
                <h4 onClick={() => this.toUserInfo(data.userId)} style={{ color: 'darkorange', marginLeft: '4%', cursor: 'pointer' }}>{data.loginName}</h4>
                <h5
                  style={{ fontSize: '10px', color: 'gray', marginLeft: '4%', marginTop: '-10px' }}
                >
                  {data.createTime}
                </h5>
              </Col>
            </Row>
          }
        >
          <Row>
            <Col span={24}>
              <div id='blogContent' style={{ background: `url(${data.cover})`, backgroundAttachment: 'fixed', backgroundSize: 'cover', padding: '0 200px 0 200px' }}>
                <div className={styles.content}>
                  <h1 style={{ textAlign: 'center' }}>{data.title}</h1>
                  <h3 style={{ textAlign: 'center' }}>{data.subTitle}</h3>
                  <div id='content_main' dangerouslySetInnerHTML={{__html: data.content}}></div>
                </div>
              </div>
            </Col>
          </Row>
          {data.status == 2 &&
          <Row style={{ textAlign: 'right', marginTop: '2%' }}>
            <Col span={24}>
              分类：{data.type.split(',').map((item) => <Tag color="success">{item}</Tag>)}
              <Divider type="vertical" />
              标签：{data.label.split(',').map((item) => <Tag color="processing">{item}</Tag>)}
              <Divider type="vertical" />
              <IconText
                key="like"
                icon={<LikeOutlined onClick={() => this.blogAction('like')} style={{ color: 'orangered', cursor: 'pointer' }} />}
                text={data.likeCount}
              />
              <Divider type="vertical" />
              <IconText
                key="star"
                icon={<StarTwoTone onClick={() => this.blogAction('star')} style={{ cursor: 'pointer' }} />}
                text={data.starCount}
              />
            </Col>
          </Row>}
        </Card>
        <Card>
          {data.status == 2 && [
            <Comment
              avatar={<Avatar src={currentUser && currentUser.avatar} alt={ currentUser && currentUser.loginName} />}
              content={
                <>
                  <Form.Item>
                    <ReactEmojiEditor
                      placeholder='快来发送有趣的评论吧(=￣ω￣=)'
                      onChange={content => this.handleChg(content)}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button htmlType="submit" loading={sending} onClick={replyName ? this.reply : this.sendComment} type="primary">
                      发送
                    </Button>
                    &nbsp;&nbsp;{replyVisible &&
                    <span style={{ fontSize: '15px' }}>回复：
                      <span style={{ color: '#2ec4ff', fontWeight: '550' }}>{replyName}</span>
                      &nbsp;&nbsp;&nbsp;
                      <Tooltip title="取消回复">
                        <CloseCircleOutlined onClick={() => this.showReply('', null, null, false)} style={{ color: 'lightgray', cursor: 'pointer' }} />
                      </Tooltip>
                    </span>}
                  </Form.Item>
                </>
              }
            />,<Divider/>]}
          {data.status == 2 && (commentList && commentList.length > 0 ?
          commentList.map((item) =>
          <Comment
            actions={[
              <Tooltip key={item.id + 'likeTip'} title="点赞">
              <span onClick={() => this.like(item.id, item.loginName)}>
                {action && action.indexOf(item.id + '_like') > -1 ? <LikeFilled/> : <LikeOutlined/>}
                <span className="comment-action">{item.likeCount && item.likeCount}</span>
              </span>
              </Tooltip>,
              <Tooltip key={item.id + 'dislikeTip'} title="踩">
              <span onClick={() => this.dislike(item.id, item.loginName)}>
                {action && action.indexOf(item.id + '_dislike') > -1 ? <DislikeFilled/> : <DislikeOutlined/>}
                <span className="comment-action">{item.dislikeCount && item.dislikeCount}</span>
              </span>
              </Tooltip>,
              <span key={item.id + 'reply'} onClick={() => this.showReply(item.loginName, item.userId, item.id, true)}>回复</span>,
              currentUser && currentUser.id == data.userId &&
              <Popconfirm
                title='是否删除此条评论'
                onConfirm={() => this.deleteComments(item.id, item.loginName)}
              >
                <span key={item.id + 'delete'}>删除</span>
              </Popconfirm>
            ]}
            author={
              <Popover
                placement="right"
                arrowPointAtCenter
                content={
                  popoverContent(item)
                }
              >
                {nameLabel(item)}
              </Popover>
            }
            avatar={
              <Popover
                placement="right"
                arrowPointAtCenter
                content={
                  popoverContent(item)
                }
              >
                <Avatar onClick={() => this.toUserInfo(item.userId)} src={item.avatar} alt="avatar" />
              </Popover>
            }
            content={
              <ReactEmojiShow
                content={item.content}
              />
            }
            datetime={
              <Tooltip title={moment(item.commentTime).format('YYYY-MM-DD HH:mm:ss')}>
                <span>{moment(item.commentTime).format('YYYY-MM-DD')}</span>
              </Tooltip>
            }
          >
            {item.children &&
            <Collapse
              bordered={false}
              expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
              ghost
            >
              <Panel header={<span style={{ color: 'gray', fontSize: '12px' }}>展开此评论回复</span>} key="1">
                {item.children.map((child) =>
                  <Comment
                    actions={[
                      <Tooltip key={child.id + 'likeTip'} title="点赞">
                        <span onClick={() => this.like(child.id, child.loginName)}>
                          {action && action.indexOf(child.id + '_like') > -1 ? <LikeFilled/> : <LikeOutlined/>}
                          <span className="comment-action">{child.likeCount && child.likeCount}</span>
                        </span>
                      </Tooltip>,
                      <Tooltip key={child.id + 'dislikeTip'} title="踩">
                        <span onClick={() => this.dislike(child.id, child.loginName)}>
                          {action && action.indexOf(child.id + '_dislike') > -1 ? <DislikeFilled/> : <DislikeOutlined/>}
                          <span className="comment-action">{child.dislikeCount && child.dislikeCount}</span>
                        </span>
                      </Tooltip>,
                      <span onClick={() => this.showReply(child.loginName, child.userId, item.id, true)} key={child.id + 'reply'}>回复</span>,
                      currentUser && currentUser.id == data.userId &&
                      <Popconfirm
                        title='是否删除此条评论'
                        onConfirm={() => this.deleteComments(child.id, child.loginName)}
                      >
                        <span key={item.id + 'delete'}>删除</span>
                      </Popconfirm>
                    ]}
                    author={
                      <span>
                        <Popover
                          placement="right"
                          arrowPointAtCenter
                          content={
                            popoverContent(child)
                          }
                        >
                          {nameLabel(child)}
                        </Popover>
                        &nbsp;&nbsp;<CaretRightOutlined />&nbsp;{child.replyId != 0 && <span style={{ color: 'gray', fontSize: '14px' }}>{child.replyName}</span>}
                      </span>
                    }
                    avatar={
                      <Popover
                        placement="right"
                        arrowPointAtCenter
                        content={
                          popoverContent(child)
                        }
                      >
                        <Avatar onClick={() => this.toUserInfo(child.userId)} src={child.avatar} alt="avatar" />
                      </Popover>
                    }
                    content={
                      <ReactEmojiShow
                        content={child.content}
                      />
                    }
                    datetime={
                      <Tooltip title={moment(child.commentTime).format('YYYY-MM-DD HH:mm:ss')}>
                        <span>{moment(child.commentTime).format('YYYY-MM-DD')}</span>
                      </Tooltip>
                    }
                  />
                )}
              </Panel>
            </Collapse>}
          </Comment>
          )
          : <span>暂无评论</span>)}
        </Card>
        <BackTop/>
        </>
    );
  }
}

export default connect(({ blogInfo, loading }) => ({
  blogInfo,
  loading: loading.effects['blogInfo/queryById'],
}))(BlogInfo);
